<script setup>

import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {useUserInfoStore} from "@/stores/userInfo";
import {deleteUser, insertUser, updateUser, userList} from "@/api/user";
import {ElMessage, ElMessageBox} from "element-plus";
//分页条数据模型
const pageNo = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(5)//每页条数
const userListData = ref([])
const gender = ref('')
const username = ref('')
const dialogFormVisible = ref(false)
const titleName = ref('')
const userInfoStore = useUserInfoStore();
// 用户添加、编辑表单数据模型
const formData = ref({
  username: '',
  email: '',
  gender:'',
  role: '',
  password:'123456'
})
const form = ref(null)
const formLabelWidth = '140px'
// 获取用户列表
const getUserList = ()=>{
  const params = {
    params:{
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      username : username.value,
      gender: gender.value
    }
  }
  userList(params).then(res=>{
    if (res.success) {
      userListData.value = res.data.records
      total.value = res.data.count
    }
  })
}
onMounted(()=>{
  getUserList()
})
// 重置
const resetParams = ()=>{
  username.value = ''
  gender.value = ''
  getUserList()
}

// 当每页条数发生了变化，会调用
const handleSizeChange = (val) => {
  pageSize.value = val
  getUserList()
}
// 当当前页面发生变化，会调用
const handleCurrentChange = (val) => {
  pageNo.value = val
  getUserList()
}
// 删除用户
const deleteById=(id)=>{
  ElMessageBox.confirm(
      '确认删除吗，删除后不可恢复?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteUser({id:id}).then(res=>{
          if (res.success) {
            ElMessage.success(res.message)
            getUserList()
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

// 用户添加打开dialog
const showAddDialog=(title)=>{
  resetForm()
  titleName.value= title
  dialogFormVisible.value = true
}
// 用户添加
const addUser = () => {
  form.value.validate((valid)=>{
    if (valid) {
      insertUser(formData.value).then(res=>{
        if (res.success) {
          getUserList()
          ElMessage.success(res.message)
          dialogFormVisible.value = false
        }
      })
    }
  })
}

// 清空表单
const resetForm =(formEl)=>{
  formData.value={
    username: '',
    email: '',
    gender:'',
    role: '',
    password:'123456'
  }
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
}
// 打开编辑dialog
const showEditDialog=(row,title)=>{
  formData.value = {...row}
  titleName.value= title
  dialogFormVisible.value = true
}
// 更新用户
const editUser=()=>{
  updateUser(formData.value).then(res=>{
    if (res.success) {
      ElMessage.success(res.message);
    } else {
      ElMessage.error(res.message)
    }
    getUserList()
    dialogFormVisible.value = false
  })
}

// 表单校验
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 16, message: '长度为3-16位', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type:'email', message: '邮箱格式不准确', trigger: 'blur'},
  ],
  gender: [
    {required: true, message: '请选择性别', trigger: 'change'},
  ],
  role: [
    {required: true, message: '请选择角色', trigger: 'change'},
  ]
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户管理</span>
        <div class="extra">
          <el-button type="primary" @click="showAddDialog('添加用户')">添加用户</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="用户名：">
        <el-input v-model="username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="性别：">
        <el-select placeholder="请选择" v-model="gender">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserList">搜索</el-button>
        <el-button @click="resetParams">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 用户列表 -->
    <el-table :data="userListData" style="width: 100%">
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="角色" prop="role">
        <template #default="{row}">
          <el-tag :type="row.role===1?'danger':'success'">{{row.role===1?'超级管理员':'普通会员'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="性别" prop="gender"></el-table-column>
      <el-table-column label="添加时间" prop="createTimeStr"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showEditDialog(row,'编辑用户')"></el-button>
          <el-button :disabled="userInfoStore.userInfo.id===row.id" :icon="Delete" circle plain type="danger" @click="deleteById(row.id)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>

<!--  添加用户表单-->
  <el-dialog v-model="dialogFormVisible" :title="titleName" width="500">
    <el-form :model="formData" ref="form"  :rules="rules">
      <el-form-item label="用户名称" :label-width="formLabelWidth" prop="username">
        <el-input  autocomplete="off" v-model="formData.username" />
      </el-form-item>
      <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
        <el-input  autocomplete="off" v-model="formData.email" />
      </el-form-item>
      <el-form-item label="角色" :label-width="formLabelWidth" prop="role">
        <el-select  placeholder="请选择" v-model="formData.role">
          <el-option label="超管" :value="1" />
          <el-option label="普通会员" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
        <el-select  placeholder="请选择" v-model="formData.gender">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="性别" :label-width="formLabelWidth">-->
<!--        <el-radio-group v-model="formData.gender">-->
<!--          <el-radio value="男" size="large">男</el-radio>-->
<!--          <el-radio value="女" size="large">女</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(form)">取消</el-button>
        <el-button type="primary" @click="titleName==='添加用户'?addUser():editUser()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>